package com.lbiuse.wx.util;

import java.beans.PropertyDescriptor;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 * @author jinglupeng.cc
 */
public class MapUtil {

	/**
	 * 根据key对map进行排序
	 * 
	 * @param map
	 * @return
	 */
	public static LinkedHashMap<String, String> sort(Map<String, String> map) {
		LinkedHashMap<String, String> tempMap = new LinkedHashMap<String, String>();
		List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(
				map.entrySet());
		Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {
			public int compare(Map.Entry<String, String> o1,
					Map.Entry<String, String> o2) {
				return (o1.getKey()).toString().compareTo(o2.getKey());
			}
		});
		for (int i = 0; i < infoIds.size(); i++) {
			Map.Entry<String, String> item = infoIds.get(i);
			tempMap.put(item.getKey(), item.getValue());
		}
		return tempMap;
	}

	/**
	 * 将简单bean 转换成为map
	 * 
	 * @param bean
	 * @return
	 */
	public static Map<String, String> fromBean(Object bean) {
		Map<String, String> map = new HashMap<String, String>();
		Class<?> clazz = bean.getClass();
		Field[] fields = clazz.getDeclaredFields();
		for (int i = 0; i < fields.length; i++) {
			try {
				String fieldName = fields[i].getName();
				PropertyDescriptor pd = new PropertyDescriptor(fieldName, clazz);
				if (pd.getReadMethod() != null) {
					Method readMethod = pd.getReadMethod();
					if (!Modifier.isPublic(readMethod.getDeclaringClass()
							.getModifiers())) {
						readMethod.setAccessible(true);
					}
					Object value = readMethod.invoke(bean);
					if (value == null) {
						continue;
					}
					map.put(fieldName, value.toString());
				}
			} catch (Exception e) {
				// TODO　当某个属性不合法时，直接忽略
			}
		}
		return map;
	}

	/**
	 * key-value拼接为queryString
	 * 
	 * @param map
	 * @param keyLower
	 * @param valueUrlencode
	 * @return
	 */
	public static String join(Map<String, String> map) {
		StringBuffer sb = new StringBuffer();
		for (String key : map.keySet()) {
			String value = map.get(key);
			if (value == null || "".equals(value)) {
				continue;
			}
			sb.append(key).append("=").append(value).append("&");
		}
		if (sb.length() > 0) {
			sb.deleteCharAt(sb.length() - 1);
		}
		return sb.toString();
	}

	/**
	 * key-value拼接为queryString
	 * 
	 * @param map
	 * @param keyLower
	 * @param valueUrlencode
	 * @return
	 */
	public static String join(Map<String, String> map, boolean urlencode) {
		StringBuffer sb = new StringBuffer();
		for (String key : map.keySet()) {
			String value = map.get(key);
			if (value == null || "".equals(value)) {
				continue;
			}
			try {
				value = (urlencode ? URLEncoder.encode(value, "UTF-8") : value);
				sb.append(key).append("=").append(value).append("&");
			} catch (UnsupportedEncodingException e) {
			}
		}
		if (sb.length() > 0) {
			sb.deleteCharAt(sb.length() - 1);
		}
		return sb.toString();
	}

	/**
	 * 简单 xml 转换为 Map
	 * 
	 * @param reader
	 * @return
	 * @throws DocumentException
	 */
	public static Map<String, String> fromXml(String xml) {
		Map<String, String> map = new HashMap<String, String>();
		try {
			Document document = DocumentHelper.parseText(xml);
			Element root = document.getRootElement();
			@SuppressWarnings("unchecked")
			List<Element> elements = root.elements();
			for (Element element : elements) {
				map.put(element.getName(), element.getText());
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return map;
	}

}
